'use client';

import LoadPage from '@/app/[locale]/load/load';
import ErrorPage from '@/app/[locale]/error/error';
import { clientQueryPostDetails, postView } from '@/services/api';
import { toRelativeTime } from '@/lib/tool';
import { usePathname } from 'next/navigation';
import type {
  IPostClientDetails,
  IPostComment,
  IQueryParams,
} from '@/interfaces';
import { useEffect, useRef, useState } from 'react';
import type { TBody, TMetadata } from '@/types';
import { useInfiniteQuery, useMutation } from '@tanstack/react-query';
import useToast from '@/hooks/useToast';
import FooterH5IcpPage from '@/app/[locale]/mobile/footerH5Icp';
import FooterH5Page from '@/app/[locale]/mobile/footerH5';
import { PostIdH5PageContext } from '@/contexts/mobile/PostId';
import NamePostIdH5Page from '@/app/[locale]/mobile/posts/[id]/name';
import ContentPostIdH5Page from '@/app/[locale]/mobile/posts/[id]/content';
import ButtonAreaPostIdH5Page from '@/app/[locale]/mobile/posts/[id]/buttonArea';
import StatementPostIdH5Page from '@/app/[locale]/mobile/posts/[id]/statement';
import CommentPostIdH5Page from '@/app/[locale]/mobile/posts/[id]/comment';
import LoadMoreBtn from '@/app/[locale]/mobile/posts/[id]/loadMoreBtn';

export default function PostIdH5Page({ metadata }: { metadata: TMetadata }) {
  const viewRef = useRef(false);
  const pathname = usePathname();

  const postViewMutation = useMutation(async (variables: TBody<void>) => {
    await postView(variables);
  });

  useEffect(() => {
    const current = viewRef.current;
    if (!current && pathname) {
      const strings = pathname.split('/');
      postViewMutation.mutate({
        id: strings[strings.length - 1],
      });
      viewRef.current = true;
    }
  }, []);

  return (
    <>
      <PostId metadata={metadata} />
      <FooterH5IcpPage metadata={metadata} />
      <FooterH5Page metadata={metadata} />
    </>
  );
}

const PostId = ({ metadata }: { metadata: TMetadata }) => {
  const { show } = useToast();
  const [pages, setPages] = useState<IPostComment[]>(
    (metadata.all['postId'].v as IPostClientDetails).data.content,
  );
  const [isClickLoadMore, setIsClickLoadMore] = useState(false);

  const clientQueryPostDetailsQuery = useInfiniteQuery(
    metadata.all['postId'].k,
    async (context) => {
      return (await clientQueryPostDetails({
        id: context.queryKey[3],
        query: {
          ...(context.queryKey[5] as IQueryParams),
          ...context.pageParam,
        },
      })) as IPostClientDetails;
    },
    {
      enabled: isClickLoadMore,
      keepPreviousData: true,
      getPreviousPageParam: (firstPage) => {
        if (firstPage.data.pageable.previous) {
          return {
            page: Math.max(firstPage.data.pageable.page - 1, 0),
            size: firstPage.data.pageable.size,
          };
        }
      },
      getNextPageParam: (lastPage) => {
        if (lastPage.data.pageable.next) {
          return {
            page: Math.min(
              lastPage.data.pageable.page + 1,
              lastPage.data.pageable.pages,
            ),
            size: lastPage.data.pageable.size,
          };
        }
      },
      initialData: () => {
        return {
          pages: [metadata.all['postId'].v as IPostClientDetails],
          pageParams: [
            {
              page: Math.max(
                ((metadata.all['postId'].k[5] as IQueryParams).page ?? 1) - 1,
                0,
              ),
              size: (metadata.all['postId'].k[5] as IQueryParams).size,
            },
          ],
        };
      },
    },
  );

  useEffect(() => {
    if (clientQueryPostDetailsQuery.data) {
      setPages(
        clientQueryPostDetailsQuery.data.pages
          .flatMap((item) => {
            item.basic._contentUpdatedOnText = toRelativeTime(
              item.basic.contentUpdatedOn,
            );
            return item.data.content;
          })
          .map((item) => {
            item.comment._createdOnText = toRelativeTime(
              item.comment.createdOn,
            );
            item.content.forEach((value) => {
              value.reply._createdOnText = toRelativeTime(
                value.reply.createdOn,
              );
            });
            return item;
          }),
      );
    }
  }, [clientQueryPostDetailsQuery.data]);

  async function onClickLoadMore() {
    try {
      setIsClickLoadMore(true);
      await clientQueryPostDetailsQuery.fetchNextPage();
    } catch (e) {
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  if (clientQueryPostDetailsQuery.data) {
    const postData = clientQueryPostDetailsQuery.data.pages[0];
    const style = (postData.basic.styles || []).find(
      (value) => value.type === 'NAME',
    );

    return (
      <PostIdH5PageContext.Provider
        value={{
          metadata,
        }}
      >
        <div className="col p-2 vstack gap-2">
          <div className="card rounded-5 border-0">
            <div className="card-body">
              <div className="vstack gap-4">
                <NamePostIdH5Page
                  item={postData.basic}
                  id={postData.basic.id}
                  name={postData.basic.name}
                  contentUpdatedOn={postData.basic.contentUpdatedOn}
                  _contentUpdatedOnText={postData.basic._contentUpdatedOnText}
                  user={postData.user}
                  badges={postData.basic.badges}
                  style={style}
                  createdBy={postData.basic.createdBy}
                />

                <ContentPostIdH5Page content={postData.content} />

                <StatementPostIdH5Page statement={postData.basic.statement} />

                <ButtonAreaPostIdH5Page
                  id={postData.basic.id}
                  name={postData.basic.name}
                  like={postData.isLike}
                  likeNum={postData.details.likeCount}
                  follow={postData.isFollow}
                  followNum={postData.details.followCount}
                  favourite={postData.isFavourite}
                  favouriteNum={postData.details.favoriteCount}
                  alias={postData.user.alias}
                />
              </div>
            </div>
          </div>

          {postData.data.content.length > 0 && (
            <div className="card rounded-5 border-0">
              <div className="card-body">
                <div className="vstack gap-4">
                  <div>全部回复</div>
                  <CommentPostIdH5Page data={postData.data} />
                  <LoadMoreBtn
                    isDisabled={
                      !clientQueryPostDetailsQuery.hasNextPage ||
                      clientQueryPostDetailsQuery.isFetchingNextPage
                    }
                    isLoading={clientQueryPostDetailsQuery.isFetchingNextPage}
                    onClickLoadMore={onClickLoadMore}
                  />
                </div>
              </div>
            </div>
          )}
        </div>
      </PostIdH5PageContext.Provider>
    );
  }

  if (clientQueryPostDetailsQuery.error) {
    return <ErrorPage error={clientQueryPostDetailsQuery.error} />;
  }

  return <LoadPage />;
};
